# coding=utf-8
import json
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME, login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import get_current_site
from django.db import transaction
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.template.response import TemplateResponse
from django.utils.http import is_safe_url
from django.utils.simplejson import JSONEncoder
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from com.kjssoft.common.globals import EagleyeAssist
from com.kjssoft.common.views import ViewErrorCode
from com.kjssoft.eagleye.forms import RegisterForm, UserProfileResetForm, UserAuthorizeForm
from com.kjssoft.eagleye.models import EEUser
from com.kjssoft.eagleye.social.models import Application, Bind

__author__ = 'daihaibin'

class EEUserJsonEncoder(JSONEncoder):
    def default(self, o):
        if o:
            if isinstance(o, EEUser):
                return {
                    'id':o.id,
                    'nickname':o.profile.nickname.value
                }
        return super(EEUserJsonEncoder, self).default(o)


@sensitive_post_parameters()
@csrf_protect
@never_cache
def login_view_page(request, template_name='kjs/eagleye/login.html',
                    redirect_field_name=REDIRECT_FIELD_NAME,
                    authentication_form=UserAuthorizeForm,
                    current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    binds = None
    if request.app and isinstance(request.app, Application):
        binds = Bind.objects.filter(application = request.app)
    if request.POST:
        form = authentication_form(data=request.POST)
        if form.is_bound and form.is_valid():
            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security check complete. Log the user in.
            login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'binds':binds
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
        current_app=current_app)

def login_when_registered(username, password, request):
    auth_user = authenticate(username = username, password = password)
    if not auth_user is None and auth_user.is_active:
        #注册即登陆
        login(request, auth_user)

@sensitive_post_parameters()
@csrf_protect
@never_cache
@transaction.commit_on_success
def register_view_page(request):
    if request.POST:
        form = RegisterForm(request.POST)
        if form.is_bound and form.is_valid():
            form.save()
            #注册成功跳转到用户信息界面
            user = form.instance
            #用户分组, project KjsSoft所有用户都是属于组EEUser_Group
            data = form.cleaned_data
            nickname = data.get('nickname')
            user.initial(nickname)
            password = data.get('password1')
            login_when_registered(user.username, password, request)
            return redirect(profile_view_page)
    else:
        form = RegisterForm(initial={})
    return render_to_response(
        'kjs/eagleye/register.html',
        {'form':form},
        context_instance=RequestContext(request)
    )

def email_verify_view_page(request, user):
    return render_to_response(
        'kjs/eagleye/register.html',
        {},
        context_instance=RequestContext(request)
    )

@login_required(login_url=EagleyeAssist.get_login_url())
def profile_view_page(request):
    return render_to_response(
        'kjs/eagleye/profile.html',
        {},
        context_instance=RequestContext(request)
    )

@login_required(login_url=EagleyeAssist.get_login_url())
@transaction.commit_on_success
def profile_reset_view_page(request):
    json_value = ViewErrorCode(10101, 'Invalid profiles meta data to reset user profiles.').to_json()
    if request.POST:
        form = UserProfileResetForm(request.POST)
        if form.is_bound and form.is_valid():
            data = form.cleaned_data
            profiles = data.get('profiles')
            for profile in profiles:
                request.user.profile.set_profile(profile.get('goods'), value = profile.get('value'))
            json_value = json.dumps(profiles)
    return HttpResponse(json_value, mimetype='text/json')